package cn.lhn.ridersclub.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final String JWT_SECRET = "Xz2rpA=P";

    /**
     * 创建token
     */
    public static String createToken(String id, String email) {

        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 24 * 7);

        return JWT.create()
                // 添加头部
                .withHeader(map)
                // 放入用户的id
                .withAudience(id)
                // 可以将基本信息放到claims中
                .withClaim("email", email)
                // 超时设置,设置过期的日期
                .withExpiresAt(instance.getTime())
                // 签发时间
                .withIssuedAt(new Date())
                // SECRET加密
                .sign(Algorithm.HMAC512(JWT_SECRET));
    }

    /**
     * 校验token
     */
    public static Map<String, String> verifyToken(String token) throws RuntimeException {

        DecodedJWT verify;

        try {
            verify = JWT.require(Algorithm.HMAC512(JWT_SECRET)).build().verify(token);
        }
        catch (Exception e) {
            throw new RuntimeException("认证失败");
        }

        Map<String, String> map = new HashMap<>();
        map.put("id", verify.getAudience().get(0));
        map.put("email", verify.getClaim("email").asString());

        return map;
    }
}
